<?php
class ptvManager
{
    const oviURL = 'https://payment.ovi.com/iap/1.0/purchases/verify?method=GET';
    const criteria = 'PurchaseVerificationResponse result="OK"';
    const mysite = 'http://www.izinin.fn-sandbox.net/';

    public function makePTV($ticket, $var_prodid, $db){
        $ticketbody = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'.
                '<PurchaseVerificationRequest xmlns="http://payment.ovi.com/iap"><Binary>'.
                    $ticket.'</Binary></PurchaseVerificationRequest>';
        
        
        $fields = "content=".rawurlencode($ticketbody);

        //open connection
        $ch = curl_init(self::oviURL);

        //set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

        // ENABLEME: for debugging purposes if you don't want 
        // to have SSL root certificate 
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        //execute post
        $data = curl_exec($ch);

        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        if ($curl_errno > 0) {
            echo "cURL Error ($curl_errno): $curl_error\n";
        } else if(ereg(self::criteria, $data)){
            echo self::getProductUrl($var_prodid, $db);
        }else{
            // there is broken ticket detected
            echo "HAVE2BUY";
        }
    }
    
    public function getProductUrl($var_prodid, $db){
        
        /* Setup the file that will be sent */
        $file = $db->getProductUrl($var_prodid);
        if(!file_exists($file)){
            echo "ERROR: requested product '$var_prodid' not found";
            exit;
        }

        /* Output HTTP headers that force "Save As" dialog */
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"$file\";");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".@filesize($file));

        /* Prevent the script from timing out for large files */
        set_time_limit(0);

        /* Send the entire file using @ to ignore all errors */
        @readfile($file);

        /* Exit immediately so no garbage follows the file contents */
        exit;
    }
}
?>